package com.ruicar.afs.cloud.apply.pre.loan.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.aggregate.aggregateport.AggregateApiFeign;
import com.ruicar.afs.cloud.aggregate.dto.*;
import com.ruicar.afs.cloud.apply.business.service.TSysParamConfigService;
import com.ruicar.afs.cloud.apply.common.entity.ApplyOrderInfo;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.contract.vo.ApplyStatisticsVo;
import com.ruicar.afs.cloud.apply.contract.vo.ApplyUseCarVinVo;
import com.ruicar.afs.cloud.apply.pre.approve.service.PreApproveService;
import com.ruicar.afs.cloud.apply.pre.loan.condition.ApplyReportCondition;
import com.ruicar.afs.cloud.apply.pre.loan.mapper.ApplyOrderInfoMapper;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyOrderInfoService;
import com.ruicar.afs.cloud.bizcommon.business.condition.ApplyTotalCondition;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.security.vo.RoleVo;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.MessageParamEnum;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.ResultBooleanEnum;
import com.ruicar.afs.cloud.message.sendmessage.config.MessageConfig;
import com.ruicar.afs.cloud.message.sendmessage.dto.MessageDataDto;
import com.ruicar.afs.cloud.message.sendmessage.dto.SendMessageDto;
import com.ruicar.afs.cloud.message.sendmessage.dto.SendResultInfoDto;
import com.ruicar.afs.cloud.message.sendmessage.service.MessageService;
import com.ruicar.afs.cloud.parameter.commom.enums.CustType;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: Lee
 * @date: 2020/5/13 21:20
 * @description:
 */
@Service
@Slf4j
@AllArgsConstructor
public class ApplyOrderInfoServiceImpl extends ServiceImpl<ApplyOrderInfoMapper, ApplyOrderInfo> implements ApplyOrderInfoService {

    private AggregateApiFeign aggregateApiFeign;
    private final MessageService service;
    private PreApproveService preApproveService;
    private TSysParamConfigService tSysParamConfigService;
    private  final MessageConfig messageConfig;


    /**
     * 更新订单申请状态
     *
     * @param applyNo
     * @param applyStatus
     */
    public void updateApplyStatus(String applyNo, String applyStatus) {
        ApplyOrderInfo orderInfo = this.baseMapper.selectOne(Wrappers.<ApplyOrderInfo>query().lambda()
                .eq(StringUtils.isNotEmpty(applyNo), ApplyOrderInfo::getApplyNo, applyNo));
        orderInfo.setApplyStatus(applyStatus);
        this.baseMapper.updateById(orderInfo);
    }

    /**
     * 根据审批返回报文，更新订单表信息状态,核准时间
     *
     * @param applyOrderInfo
     */
    public void updateOrderApplyStatus(ApplyOrderInfo applyOrderInfo) {
        ApplyOrderInfo orderInfo = this.baseMapper.selectOne(Wrappers.<ApplyOrderInfo>query().lambda()
                .eq(StringUtils.isNotEmpty(applyOrderInfo.getApplyNo()), ApplyOrderInfo::getApplyNo, applyOrderInfo.getApplyNo()));
        orderInfo.setApplyStatus(applyOrderInfo.getApplyStatus());
        //如果核准时间不为空，那么就录入核准时间
        if (applyOrderInfo.getRiskPassDate() != null) {
            orderInfo.setRiskPassDate(applyOrderInfo.getRiskPassDate());
        }
        if (applyOrderInfo.getApplyReporter() != null) {
            orderInfo.setApplyReporter(applyOrderInfo.getApplyReporter());
        }
        if (StringUtils.isNotEmpty(String.valueOf(applyOrderInfo.getIntoFirstDate()))) {
            orderInfo.setIntoFirstDate(applyOrderInfo.getIntoFirstDate());
        }
        if (applyOrderInfo.getCancelDate() != null) {
            orderInfo.setCancelDate(applyOrderInfo.getCancelDate());
        }
        this.baseMapper.updateById(orderInfo);
    }

    /**
     * 通过申请编号获取订单信息
     *
     * @param applyNo
     * @return
     */
    public ApplyOrderInfo getOrderInfoByApplyNo(String applyNo) {

        ApplyOrderInfo applyOrderInfo = this.baseMapper.selectOne(Wrappers.<ApplyOrderInfo>query().lambda().eq(ApplyOrderInfo::getApplyNo, applyNo));
        return applyOrderInfo;
    }

    /**
     * 通过ID获取订单信息
     *
     * @param id
     * @return
     */
    public ApplyOrderInfo getOrderInfoById(Long id) {

        ApplyOrderInfo applyOrderInfo = this.baseMapper.selectOne(Wrappers.<ApplyOrderInfo>query().lambda().eq(ApplyOrderInfo::getId, id));
        return applyOrderInfo;
    }

    /**
     * 保存订单信息
     *
     * @param applyNo
     * @param condition
     * @return
     */
    public ApplyOrderInfo saveOrderInfo(String applyNo, ApplyReportCondition condition) {

        ApplyOrderInfo orderInfo = new ApplyOrderInfo();
        orderInfo.setApplyNo(applyNo);
        orderInfo.setBusinessType(condition.getBusinessType());
        orderInfo.setOperateWay(condition.getOperateWay());
        orderInfo.setCarType(condition.getCarType());
        orderInfo.setCarNature(condition.getCarNature());
        orderInfo.setAffiliatedWay(condition.getAffiliatedWay());
        orderInfo.setCarPurpose(condition.getCarPurpose());
        orderInfo.setApplyStatus(ApplyConstants.APPLY_STATUS_DRAFT);
        if (StringUtils.isNotBlank(condition.getDealerId())) {
            orderInfo.setDealerId(condition.getDealerId());
            orderInfo.setDealerName(condition.getDealerName());
        }
        orderInfo.setSaleAdvisor(condition.getSaleAdvisor());
        orderInfo.setSalePhone(condition.getSalePhone());
        orderInfo.setRemarks(condition.getRemarks());
        orderInfo.setCustType(CustType.PERSON.getIndex());
        orderInfo.setDeptId(SecurityUtils.getUser().getDeptId().toString());// 部门ID
        orderInfo.setSellerRealName(SecurityUtils.getUser().getUserRealName());
        orderInfo.setSellerPhone(condition.getSellerPhone());
        JSONArray roleArray = SecurityUtils.getUser().getUserExtInfo().getJSONArray("roles");
        if (roleArray != null) {
            List<RoleVo> roleList = roleArray.toJavaList(RoleVo.class);
            for (RoleVo vo : roleList) {
                if ("ROLE_XCAPPLY".equals(vo.getRoleCode()) || "ROLE_APPLY".equals(vo.getRoleCode())) {
                    orderInfo.setApplyReporter(SecurityUtils.getUsername());
                }
            }
        }
        if (ObjectUtil.isNotNull(condition.getPreId())) {
            orderInfo.setPreId(condition.getPreId());// 预审批ID
        }
        this.baseMapper.insert(orderInfo);
        // add by sijun.yu 2020-9-25 同步预审批数据
        preApproveService.copyPreInfoToApply(applyNo, condition);

        return orderInfo;
    }

    /**
     * 更新订单信息
     *
     * @param orderInfo
     * @param condition
     */
    public void updateOrderInfo(ApplyOrderInfo orderInfo, ApplyReportCondition condition) {

        orderInfo.setBusinessType(condition.getBusinessType());
        orderInfo.setOperateWay(condition.getOperateWay());
        orderInfo.setCarType(condition.getCarType());
        orderInfo.setCarNature(condition.getCarNature());
        orderInfo.setAffiliatedWay(condition.getAffiliatedWay());
        orderInfo.setCarPurpose(condition.getCarPurpose());
        if (StringUtils.isNotBlank(condition.getDealerId())) {
            orderInfo.setDealerId(condition.getDealerId());
            orderInfo.setDealerName(condition.getDealerName());
        }
        orderInfo.setSaleAdvisor(condition.getSaleAdvisor());
        orderInfo.setSalePhone(condition.getSalePhone());
        orderInfo.setRemarks(condition.getRemarks());
        if (StringUtils.isEmpty(orderInfo.getApplyReporter())) {
            JSONArray roleArray = SecurityUtils.getUser().getUserExtInfo().getJSONArray("roles");
            if (roleArray != null) {
                List<RoleVo> roleList = roleArray.toJavaList(RoleVo.class);
                for (RoleVo vo : roleList) {
                    if ("ROLE_XCAPPLY".equals(vo.getRoleCode()) || "ROLE_APPLY".equals(vo.getRoleCode())) {
                        orderInfo.setApplyReporter(SecurityUtils.getUsername());
                    }
                }
            }
        }
        this.baseMapper.updateById(orderInfo);
    }

    /**
     * 获取进件申请数量
     *
     * @param channelId,status
     * @param status
     * @return
     */
    @Override
    public List<ApplyOrderInfo> getDefaultList(String channelId, String status) {
        JSONArray jsonArray = SecurityUtils.getUser().getUserExtInfo().getJSONArray("deptIds");
        List<String> deptIds = null;
        List<RoleVo> roleList = null;
        if (jsonArray != null) {
            // 部门列表
            deptIds = jsonArray.toJavaList(String.class);
        }
        JSONArray roleArray = SecurityUtils.getUser().getUserExtInfo().getJSONArray("roles");
        if (roleArray != null) {
            roleList = roleArray.toJavaList(RoleVo.class);
        }
        List<ApplyOrderInfo> applyOrderInfoList = this.baseMapper.getApplyList(channelId, status, SecurityUtils.getUsername(), deptIds, roleList);
        return applyOrderInfoList;
    }

    /**
     * 获取进件申请数量
     *
     * @param applyTotalCondition
     * @return
     */
    @Override
    public List<ApplyOrderInfo> getApplyCount(ApplyTotalCondition applyTotalCondition) {
        List<ApplyOrderInfo> applyOrderInfoList = this.baseMapper.getApplyCount(applyTotalCondition);
        return applyOrderInfoList;
    }

    /**
     * 获取进件申请数量
     *
     * @param applyTotalCondition
     * @return
     */
    @Override
    public List<ApplyStatisticsVo> getApplyCountPc(ApplyTotalCondition applyTotalCondition) {
        List<ApplyStatisticsVo> applyOrderInfoList = this.baseMapper.getApplyCountPc(applyTotalCondition);
        return applyOrderInfoList;
    }

    /**
     * @description: 二手车历史存量vin查询
     * @author jiaqi.guo
     * @created 2020/7/15 16:35
     * @version 1.0
     */
    @Override
    public List<VinInfoDto> getUsedcarHis(String vin) {
        List<VinInfoDto> vinList = new ArrayList();
        try {
            JSONObject json = aggregateApiFeign.getUsedCar(vin);
            log.info("历史存量vin查询返回JSON:-------------------------------" + json);
            if (1 == json.getInteger("success")) {
                JSONArray jsonArray = json.getJSONArray("data");
                if (jsonArray.size() > 0) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        VinInfoDto vinInfo = JSONObject.parseObject(JSONObject.toJSONString(jsonArray.get(i)), VinInfoDto.class);
                        vinList.add(vinInfo);
                    }
                }
            } else {
                log.info("请求失败:" + json.getString("message"));
            }
        } catch (Exception e) {
            log.info("二手车历史存量vin异常：" + e.getMessage());
        }
        return vinList;
    }

    /**
     * @description: 历史贷款金额
     * @author jiaqi.guo
     * @created 2020/7/16 11:33
     * @version 1.0
     */
    @Override
    public BigDecimal getLoanhistory(CertNoDto certNoDto) {
        BigDecimal loanAmount = BigDecimal.ZERO;
        try {
            JSONObject json = aggregateApiFeign.getLoanhistory(certNoDto.getBorrowerCertno(), certNoDto.getCoborrowerCertno());
            log.info("历史贷款额度返回JSON:-------------------------------" + json);
            if (1 == json.getInteger("success")) {
                JSONArray jsonArray = json.getJSONArray("data");
                if (jsonArray.size() > 0) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        CertNoDto cerNo = JSONObject.parseObject(JSONObject.toJSONString(jsonArray.get(i)), CertNoDto.class);
                        loanAmount = loanAmount.add(cerNo.getLoanAmount());
                    }
                }
            } else {
                log.info("请求失败:" + json.getString("message"));
            }
        } catch (Exception e) {
            log.info("历史贷款额度异常：" + e.getMessage());

        }
        return loanAmount;
    }

    @Override
    public void sendApplyMessageInfo(String phone) {
        SendMessageDto messageDto = new SendMessageDto();
        messageDto.setChannel("1");
        messageDto.setCode(MessageParamEnum.CODE.getCode());
        messageDto.setTimestamp(System.currentTimeMillis() / 1000 + "");
        messageDto.setUid(messageConfig.getUid());
        List<MessageDataDto> dataDtoList = new ArrayList<>();
        MessageDataDto dataDto = new MessageDataDto();
        dataDto.setDeptId(MessageParamEnum.CODE_003.getCode());
        dataDto.setOrigin(MessageParamEnum.ORIGIN.getCode());
        dataDto.setPhone(phone);
        dataDto.setSummaryId(phone + (new Date()).getTime());
        dataDto.setSmsContent("尊敬的客户，您的汽车贷款申请已经提交，请保持手机畅通，注意接听022-65276701至022-65276750区间的电话回访。");
        dataDto.setTemplateId("W201");
        dataDto.setPriority("1");
        dataDtoList.add(dataDto);

        messageDto.setMessageDataDto(dataDtoList);
        SendResultInfoDto sendResultInfoDto = service.sendMessageData(messageDto);
        if (ObjectUtils.isNotEmpty(sendResultInfoDto)) {
            if (sendResultInfoDto.getResult().equals(ResultBooleanEnum.TRUE.getCode())) {
            } else {
                throw new AfsBaseException("进件数据异常！");
            }
        } else {
            throw new AfsBaseException("短信接口响应失败！");
        }
    }

    @Override
    public List<ApplyUseCarVinVo> getOrderInfoByVin(String vin) {
        List<ApplyUseCarVinVo> applyUseCarVinVoList = this.baseMapper.getOrderInfoByVin(vin);
        return applyUseCarVinVoList;
    }

    /**
     * @description: 放款vin查重查
     * @author panhj
     * @created 2020/9/17 16:35
     * @version 1.0
     */
    @Override
    public List<VinCheckDto> getLoanVinCheck(String vin) {
        String value = tSysParamConfigService.getParamValue("aggregate-system", "getLoanhistory", "");
        if (!value.equals(ApplyConstants.YES)) {
            log.info("聚合接口关闭");
            return null;
        }
        List<VinCheckDto> vinList = new ArrayList();
        try {
            JSONObject json = aggregateApiFeign.loanperiod(vin);
            log.info("放款vin查重查询返回JSON:-------------------------------" + json);
            if (1 == json.getInteger("success")) {
                JSONArray jsonArray = json.getJSONArray("data");
                if (jsonArray.size() > 0) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        VinCheckDto vinInfo = JSONObject.parseObject(JSONObject.toJSONString(jsonArray.get(i)), VinCheckDto.class);
                        vinList.add(vinInfo);
                    }
                }
            } else {
                log.info("请求失败:" + json.getString("message"));
            }
        } catch (Exception e) {
            log.info("放款vin查重异常：" + e.getMessage());
        }
        return vinList;
    }

    /**
     * @description: 身份证验重
     * @author panhj
     * @created 2020/9/17 11:33
     * @version 1.0
     */
    @Override
    public List<CertNoCheckDto> getCertNoCheckInfo(CertNoDto certNoDto) {
        String value = tSysParamConfigService.getParamValue("aggregate-system", "getLoanhistory", "");
        if (!value.equals(ApplyConstants.YES)) {
            log.info("聚合接口关闭");
            return null;
        }
        List<CertNoCheckDto> vinList = new ArrayList();
        try {
            JSONObject json = aggregateApiFeign.checkcertnorepeat(certNoDto.getBorrowerCertno(), certNoDto.getCoborrowerCertno(), certNoDto.getGuarantorCertno());
            log.info("身份证验重返回JSON:-------------------------------" + json);
            if (1 == json.getInteger("success")) {
                JSONArray jsonArray = json.getJSONArray("data");
                if (jsonArray.size() > 0) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        CertNoCheckDto cerNo = JSONObject.parseObject(JSONObject.toJSONString(jsonArray.get(i)), CertNoCheckDto.class);
                        vinList.add(cerNo);
                    }
                }
            } else {
                log.info("请求失败:" + json.getString("message"));
            }
        } catch (Exception e) {
            log.info("身份证验重异常：" + e.getMessage());

        }
        return vinList;
    }


    /**
     * @description: 二手车进件申请VIN验重
     * @author panhj
     * @created 2020/9/17 16:35
     * @version 1.0
     */
    @Override
    public List<UsedVinInfoDto> getUsedVinInfo(String vin) {
        String value = tSysParamConfigService.getParamValue("aggregate-system", "getLoanhistory", "");
        if (!value.equals(ApplyConstants.YES)) {
            log.info("聚合接口关闭");
            return null;
        }
        List<UsedVinInfoDto> vinList = new ArrayList();
        try {
            JSONObject json = aggregateApiFeign.usedcarcheck(vin);
            log.info("二手车进件申请VIN验重查询返回JSON:-------------------------------" + json);
            if (1 == json.getInteger("success")) {
                JSONArray jsonArray = json.getJSONArray("data");
                if (jsonArray.size() > 0) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        UsedVinInfoDto vinInfo = JSONObject.parseObject(JSONObject.toJSONString(jsonArray.get(i)), UsedVinInfoDto.class);
                        vinList.add(vinInfo);
                    }
                }
            } else {
                log.info("请求失败:" + json.getString("message"));
            }
        } catch (Exception e) {
            log.info("二手车进件申请VIN验重异常：" + e.getMessage());
        }
        return vinList;
    }

    /**
     * @description: 网约车挂靠公司信审
     * @author panhj
     * @created 2020/9/17 16:35
     * @version 1.0
     */
    @Override
    public AffiliatedCheckDto getAffiliatedCheckInfo(String creditCode, int limitNumber) {
        String value = tSysParamConfigService.getParamValue("netCar", "switch", "");
        if (!value.equals(ApplyConstants.YES)) {
            log.info("聚合接口关闭");
            return null;
        }
        AffiliatedCheckDto affiliatedCheckDto = new AffiliatedCheckDto();
        try {
            JSONObject json = aggregateApiFeign.affiliatedcheck(creditCode, limitNumber);
            log.info("网约车挂靠公司信审查询返回JSON:-------------------------------" + json);
            if (1 == json.getInteger("success")) {
                JSONObject jsonObject = json.getJSONObject("data");
                affiliatedCheckDto = JSONObject.parseObject(JSONObject.toJSONString(jsonObject), AffiliatedCheckDto.class);
            } else {
                log.info("请求失败:" + json.getString("message"));
            }
        } catch (Exception e) {
            log.info("网约车挂靠公司信审异常：" + e.getMessage());
        }
        return affiliatedCheckDto;
    }
}
